#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <assert.h>
#include <stdlib.h>

#define NUM 1024
struct MyFILE_{
    int fd;
    char buffer[1024];
    int end; 
};

typedef struct MyFILE_ MyFILE;

MyFILE *fopen_(const char *pathname,const char *mode)
{
    assert(pathname);
    assert(mode);
    MyFILE *fp=NULL;
    if(strcmp(mode,"r")==0){}
    else if(strcmp(mode,"r+")==0){}
    else if(strcmp(mode,"w")==0)
    {
        int fd=open(pathname,O_WRONLY|O_TRUNC|O_CREAT,0666);
        if(fd>=0)
        {
            fp=(MyFILE*)malloc(sizeof(MyFILE));
            memset(fp,0,sizeof(MyFILE));
            fp->fd=fd;
        }
    }
    
    else if(strcmp(mode, "w+") == 0){}
    else if(strcmp(mode, "a") == 0){}
    else if(strcmp(mode, "a+") == 0){}
    else{//什么都不做
    }
    return fp;
}

void fputs_(const char *message,MyFILE *fp)
{
    assert(message);
    assert(fp);

    strcpy(fp->buffer+fp->end,message);
    fp->end+=strlen(message);
   
    //for debug
    printf("%s\n", fp->buffer);

    if(fp->fd==0){
        //标准输入
    }
    else if(fp->fd==1)
    {
        //标准输出
        if(fp->buffer[fp->end-1]=='\n')
        {
            write(fp->fd,fp->buffer,fp->end);
            fp->end=0;
        }
    }
    else if(fp->fd == 2)
    {
        //标准错误
    }
    else
    {
        //其他文件
    }
}

void fflush_(MyFILE*fp)
{
    assert(fp);
    if(fp->end!=0)
    {
        write(fp->fd,fp->buffer,fp->end);
        syncfs(fp->fd);//将数据写入到硬盘
        fp->end=0;
    }
}

void fclose_(MyFILE *fp)
{
    assert(fp);
    fflush_(fp);
    close(fp->fd);
    free(fp);
}

int main()
{
    //close(1);
    MyFILE *fp = fopen_("./log.txt", "w");
    if(fp == NULL)
    {
        printf("open file error");
        return 1;
    }

    fputs_("one: hello world", fp);

    fork();

    fclose_(fp);
}
